#!/bin/bash

# 喵趣AI项目启动脚本

echo "======================================"
echo "       喵趣AI 项目启动脚本"
echo "======================================"

# 检查环境依赖
check_requirements() {
    echo "检查环境依赖..."
    
    # 检查Python
    if ! command -v python3 &> /dev/null; then
        echo "❌ Python3 未安装"
        exit 1
    fi
    echo "✅ Python3 已安装: $(python3 --version)"
    
    # 检查Node.js
    if ! command -v node &> /dev/null; then
        echo "❌ Node.js 未安装"
        exit 1
    fi
    echo "✅ Node.js 已安装: $(node --version)"
    
    # 检查MySQL
    if ! command -v mysql &> /dev/null; then
        echo "⚠️  MySQL 未安装或未在PATH中"
    else
        echo "✅ MySQL 已安装"
    fi
    
    # 检查Redis
    if ! command -v redis-server &> /dev/null; then
        echo "⚠️  Redis 未安装或未在PATH中"
    else
        echo "✅ Redis 已安装"
    fi
}

# 安装后端依赖
install_backend() {
    echo "安装后端依赖..."
    cd backend
    
    # 创建虚拟环境
    if [ ! -d "venv" ]; then
        python3 -m venv venv
        echo "✅ 创建虚拟环境"
    fi
    
    # 激活虚拟环境并安装依赖
    source venv/bin/activate
    pip install -r requirements.txt
    echo "✅ 后端依赖安装完成"
    
    cd ..
}

# 安装前端依赖
install_frontend() {
    echo "安装前端依赖..."
    cd frontend
    
    # 安装npm依赖
    npm install
    echo "✅ 前端依赖安装完成"
    
    cd ..
}

# 初始化数据库
init_database() {
    echo "初始化数据库..."
    echo "请确保MySQL服务已启动，并按照docs/deployment.md创建数据库"
    
    cd backend
    source venv/bin/activate
    
    # 检查.env文件
    if [ ! -f ".env" ]; then
        cp .env.example .env
        echo "✅ 创建.env配置文件，请编辑数据库连接信息"
    fi
    
    cd ..
}

# 启动服务
start_services() {
    echo "启动项目服务..."
    
    # 启动Redis（如果需要）
    if command -v redis-server &> /dev/null; then
        echo "启动Redis..."
        redis-server --daemonize yes
    fi
    
    # 启动后端服务
    echo "启动后端服务..."
    cd backend
    source venv/bin/activate
    
    # 启动Flask应用（后台运行）
    nohup python run.py > ../logs/backend.log 2>&1 &
    FLASK_PID=$!
    echo "✅ 后端服务已启动 (PID: $FLASK_PID)"
    
    # 启动Celery worker（后台运行）
    nohup celery -A tasks.image_generation.celery worker --loglevel=info > ../logs/celery.log 2>&1 &
    CELERY_PID=$!
    echo "✅ Celery worker已启动 (PID: $CELERY_PID)"
    
    cd ..
    
    # 启动前端开发服务器
    echo "启动前端服务..."
    cd frontend
    npm run dev &
    FRONTEND_PID=$!
    echo "✅ 前端服务已启动 (PID: $FRONTEND_PID)"
    
    cd ..
    
    # 保存PID到文件
    mkdir -p logs
    echo $FLASK_PID > logs/flask.pid
    echo $CELERY_PID > logs/celery.pid
    echo $FRONTEND_PID > logs/frontend.pid
    
    echo ""
    echo "======================================"
    echo "🚀 所有服务已启动完成！"
    echo "======================================"
    echo "前端访问地址: http://localhost:5173"
    echo "后端API地址: http://localhost:5000"
    echo ""
    echo "日志文件位置:"
    echo "- 后端日志: logs/backend.log"
    echo "- Celery日志: logs/celery.log"
    echo ""
    echo "停止服务请运行: ./stop.sh"
    echo "======================================"
}

# 主函数
main() {
    case "$1" in
        "install")
            check_requirements
            install_backend
            install_frontend
            init_database
            ;;
        "start")
            start_services
            ;;
        "")
            check_requirements
            install_backend
            install_frontend
            init_database
            start_services
            ;;
        *)
            echo "用法: $0 [install|start]"
            echo "  install - 仅安装依赖和初始化"
            echo "  start   - 仅启动服务"
            echo "  (无参数) - 执行完整安装和启动流程"
            exit 1
            ;;
    esac
}

main "$1"